<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/26
 * Time: 11:07
 */

namespace Admin\Controller;

class CategoryController extends CommenController
{
   public function index(){
	   $cate = M('category')->order('sort')->select();
	   $cate = level($cate);//分配变量
//	   $this->p($cate);
	   $this->assign('cate',$cate);
	   //加载模板
	   $this->display();
   }
	/**
	 * 添加分类
	 */
	public function add(){
		if(IS_POST){
//			$this->p($_POST);
			if(M('category')->add($_POST)){
				$this->success('添加成功', U('index'));
				die;
			}else{
				$this->error('添加失败');
				die;
			}
		}

		//分配父级ID
		$pid = isset($_GET['pid']) ? (int) $_GET['pid'] : 0;
		$this->assign('pid',$pid);

		//如果添加的是子分类，分配类型选择，即顶级分类没有类型
		if($this->pid > 0){
			$type = M('type')->select();
			$this->assign('type',$type);
		}

		$this->display();

	}

	/**
	 * 编辑
	 */
	public function edit(){
		$cid = I('get.cid');
//		$this->p($cid);
		$oldData = M('category')->where(['cid'=>$cid])->getField('cname');
//		$this->p($oldData);
		$this->oldData = $oldData;//分配变量
		if(IS_POST){
			//$this->p($_POST);
			if(M('category')->where(['cid'=>$cid])){
				$data =[
					'cid'=>$cid,
					'cname'=>$_POST['cname']
				];
				M('category')->save($data);
				$this->success('修改成功', U('index'));
				die;
			}else{
				$this->error('修改失败');
				die;
			}
		}
		$this->display();

	}
	/**
	 * 删除
	 */
	public function del(){
		$cid = I('get.cid');
//		$this->p($cid);
		$cate = M('category')->field(['cid', 'pid',])->select();
//		$this->p($cate);die;
		$cids = get_childs_id($cate, $cid);
//		$this->p($cids);die;
		$cids[] = $cid;
//		$this->p($cids);die;
		$where = array('cid' => array('IN', $cids));
//		$this->p($where);
		if(M('category')->where($where)->delete()){
			$this->success('删除成功', U('index'));
		}else{
			$this->error('删除失败');
		}
	}

}